<!--create by cws-->
<template>
  <div>
    <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="130px">
      <el-form-item label="商品属性&sku" prop="name">
        <el-select v-model="selected" placeholder="请选择" clearable filterable :style="{width: '30%'}">
          <el-option v-for="(item, index) in attrList" :key="index" :label="item" :value="item">
          </el-option>
        </el-select>
        <el-button type="info" style="margin: 0 5px" @click="addTable">(1)添加sku</el-button>
        <el-button type="info" style="margin: 0 5px" @click="addColumn">(2)添加属性</el-button>
        <el-button type="danger" style="margin: 0 5px" @click="removeColumn">删除列</el-button>
        <el-button style="margin: 0 5px" @click="reset">重置</el-button>
        <el-button type="primary" v-hasPermi="['shopping:attribute:add']" @click="addAttr">添加新属性</el-button>
<!--        <el-button type="primary" @click="test">测试</el-button>-->
        <div>
          <el-table :data="formData.tableData" v-if="formData.showTable" style="width: 100%">
            <el-table-column v-for="column in formData.columns" :key="column.prop" :label="column.label"
                             :prop="column.prop">
              <template slot-scope="scope">
                <el-input v-model="scope.row[column.prop]" placeholder="请输入内容"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="danger" @click="handleDeleteRow(scope.$index)">删除行</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-row style="color: red;font-size: 10px;">
          注意:如不设置sku属性，则默认为商品基本信息的销售价作为价格
        </el-row>
      </el-form-item>
      <el-form-item label="商品默认图片" prop="defaultImg">
        <el-upload class="avatar-uploader" name="multipartFile" :action="uploadImgUrl" :show-file-list="false"
                   :headers="headers" :on-success="UploadSuccessDefaultImage">
          <img v-if="formData.defaultImg" :src="formData.defaultImg" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="商品滑动图" prop="albumPics">
        <el-upload name="multipartFile" class="upload-demo" :headers="headers" :action="uploadImgUrl"
                   :on-success="handleAlbumPics" :on-remove="handleRemoveList" :file-list="formData.albumPics"
                   :limit="5"
                   list-type="picture">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过5000kb</div>
        </el-upload>
      </el-form-item>
    </el-form>
<!--     <el-button @click="testImage">测试</el-button>-->

    <!--  添加新属性  -->
    <el-dialog title="添加新属性" :visible.sync="dialogAddShow" width="30%">
      <div>
        <el-input v-model="attrName" placeholder="请输入属性名"></el-input>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogAddShow = false">取 消</el-button>
        <el-button type="primary" @click="affrimAttr">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {getArrtName} from '@/api/common/common';
import {addAttribute} from "@/api/shopping/attribute";
import {getToken} from "@/utils/auth";
import Vue from 'vue';

export default {
  name: 'sku',
  props: {
    value: [Object]
  },
  data() {
    return {
      formData: {
        defaultImg: "",
        albumPics: [],
        showTable: false,
        columns: [
          {label: '销售价格', prop: 'salePrice'},
          {label: '促销价格', prop: 'promotionPrice'},
          {label: '商品库存', prop: 'stock'},
          {label: '库存预警值', prop: 'warningStock'}
        ],
        tableData: [],
      },
      selected: '',
      attrList: [],
      rules: {
        defaultImg: [{
          required: true,
          message: '请上传商品图片',
          trigger: 'change'
        }],
        albumPics: [{
          required: true,
          message: '请上传商品图片',
          trigger: 'change'
        }],
      },
      attrName: "",
      dialogAddShow: false,
      number: 0,
      uploadList: [],
      dialogImageUrl: "",
      dialogVisible: false,
      hideUpload: false,
      baseUrl: process.env.VUE_APP_BASE_API,
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/oss/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      }
    };
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          this.formData = val;
        }
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
    this.getAttrNames();
  },
  methods: {
    handleRemoveList(file, fileList) {
      this.formData.albumPics = this.formData.albumPics.filter(item => item.name !== file.name);
    },
    UploadSuccessDefaultImage(res, file) {
      if (res.code == 200) {
        Vue.set(this.formData, "defaultImg", res.fileName)
      }
    },
    handleAlbumPics(res, file) {
      if (res.code == 200) {
        this.$set(this.formData.albumPics, this.formData.albumPics.length, {url: res.fileName, name: res.fileName});
      }
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    testImage() {
      console.log(this.formData)
    },
    /** 添加属性 */
    addAttr() {
      this.attrName = "";
      this.dialogAddShow = true;
    },
    /** 确认添加新属性 */
    affrimAttr() {
      if (!this.attrName) {
        this.$message.error('请输入属性名');
        return;
      }
      let from = {
        name: this.attrName
      }
      addAttribute(from).then(res => {
        if (res.code == 200) {
          this.dialogAddShow = false
          this.getAttrNames();
          this.$message.success('添加成功');
        }
      });
    },
    /** 转换格式*/
    transformData(row) {
      const excludeKeys = ['promotionPrice', 'salePrice', 'stock', 'warningStock'];
      const result = [];
      for (const key in row) {
        if (row.hasOwnProperty(key) && !excludeKeys.includes(key)) {
          result.push({key, value: row[key]});
        }
      }
      return result;
    },
    /** 反转格式*/
    deTransformData(data) {
      const result = {};
      for (const item of data) {
        result[item.key] = item.value;
      }
      return result;
    },
    test() {
      console.log(this.formData.tableData)
      console.log(this.formData.columns)
      // const requiredColumns = this.columns.filter(column => column.prop !== 'warningStock');
      // let isValid = true;
      // for (const row of this.tableData) {
      //   for (const column of requiredColumns) {
      //     if (!row[column.prop]) {
      //       this.$message.error(`请填写 ${column.label}`);
      //       isValid = false;
      //       break;
      //     }
      //   }
      //   if (!isValid) break;
      // }
      // if (isValid) {
      //   const transformedData = this.transformData(this.tableData[0]);
      //   console.log(transformedData);
      // }
    },
    getAttrNames() {
      getArrtName().then(res => {
        this.attrList = res.data;
      });
    },
    addTable() {
      if (this.selected) {
        this.formData.showTable = true;
        const newRow = {};
        this.formData.columns.forEach(column => {
          Vue.set(newRow, column.prop, '');
        });
        this.formData.tableData.push(newRow);
      } else {
        this.$message.error('请选择属性');
        return;
      }
    },
    handleDeleteRow(index) {
      this.formData.tableData.splice(index, 1);
    },
    addColumn() {
      if (this.formData.tableData.length == 0) {
        this.$message.error('点击添加sku');
        return;
      }
      if (this.selected && !this.columnExists(this.selected)) {
        const newColumn = {label: this.selected, prop: this.selected};
        this.formData.columns.unshift(newColumn); // 将新列添加到最前面
        // 更新所有行的数据，确保新列有对应的值
        this.formData.tableData.forEach(row => {
          Vue.set(row, this.selected, '');
        });
      } else {
        this.$message.error('该列已存在，无法重复添加');
      }
    },
    removeColumn() {
      if (this.formData.tableData.length == 0) {
        this.$message.error('点击添加sku');
        return;
      }
      if (!this.selected) {
        this.$message.error('请选择要删除的列');
        return;
      }
      if (!this.columnExists(this.selected)) {
        this.$message.error('该列不存在，无法删除');
        return;
      }
      if (this.selected) {
        // 从columns中移除该列
        this.formData.columns = this.formData.columns.filter(column => column.prop !== this.selected);
        // 从tableData中移除该列的数据
        this.formData.tableData.forEach(row => {
          delete row[this.selected];
        });
        // 清空selected值
        this.selected = '';
      } else {
        this.$message.error('请选择要删除的列');
        return;
      }
    },
    columnExists(prop) {
      return this.formData.columns.some(column => column.prop === prop);
    },
    reset() {
      this.formData.tableData = [];
      this.formData.columns = [
        {label: '销售价格', prop: 'salePrice'},
        {label: '促销价格', prop: 'promotionPrice'},
        {label: '商品库存', prop: 'stock'},
        {label: '库存预警值', prop: 'warningStock'}
      ];
      this.formData.showTable = false;
      this.selected = '';
      // this.formData.albumPics = []
      // this.formData.defaultImg = ""
      this.attrName = ""
    },
    validateForm() {
      if (this.formData.showTable) {
        const requiredColumns = this.columns.filter(column => column.prop !== 'warningStock');
        let isValid = true;
        for (const row of this.tableData) {
          for (const column of requiredColumns) {
            if (!row[column.prop]) {
              this.$message.error(`请填写 ${column.label}`);
              isValid = false;
              break;
            }
          }
          if (!isValid) break;
        }
        if (!isValid) return
      }
      return new Promise((resolve, reject) => {
        this.$refs.elForm.validate((valid) => {
          if (valid) {
            resolve(true);
          } else {
            reject(false);
          }
        });

      });
    }
  }
};
</script>
<style scoped>
/deep/ .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

/deep/ .avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

/deep/ .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

/deep/ .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
